<template>
  <div class="store box bg clmstart">
    <!-- 消息通知 -->
    <div class="noticebox">
      <van-notice-bar color="#000000" background="#fbce07" left-icon="volume-o"
        text="积分商城将于2024年10月10日24点关闭，请还未消耗的用户尽快在有效期内进行换购。" />
    </div>
    <div class="backbox">
      <img src="@/assets/img/back.png" class="goback" @click="$router.replace('/mine')" />
    </div>
    <div class="store_container">
      <div class="store_tabs">
        <div class="tab_title_box">
          <div class="tab_title_item" :class="{ active: item.isflag }" v-for="item in tablist" :key="item.id"
            @click="change(item.id)">
            {{ item.name }}
          </div>
        </div>
        <div class="tab_container_box">
          <img src="@/assets/img/person_head.png" class="tab_head" />
          <div class="tab_container">
            <p class="my_integral">我的积分：{{ my_integral }}</p>
            <!-- 产品商城 -->
            <div class="tab_container_list clmstart" v-if="tablist[0].isflag">
              <div class="titem" v-for="item in prolist" :key="item.id">
                <div class="titem_cont">
                  <div class="titem_left">
                    <!-- 左边 -->
                    <div class="pro_box">
                      <div class="pro_bg"></div>
                      <img :src="item.poster_url" />
                    </div>
                    <a class="todetailbtn" href="javascript:;" @click="
                      $router.replace({
                        path: 'goodsdetail',
                        query: { goods_url: item.detail_url },
                      })
                      ">查看详情</a>
                  </div>
                  <!-- 右边 -->
                  <div class="titem_right">
                    <div class="topt title">{{ item.title }}</div>
                    <div class="topt price">金额：￥{{ item.price }}</div>
                    <div class="topt price">
                      混合支付：￥{{ item.discount_price }}+积分{{
                        item.points
                      }}
                    </div>
                    <div class="topt count">
                      <span>购买数量：</span>
                      <van-stepper v-model="item.count" integer step="1" input-width="62px" button-size="44px"
                        class="stepper" />
                    </div>
                    <div class="topt types">
                      <span>选择粘度：</span>
                      <input type="text" readonly v-model="item.types" @click="item.typeshow = true" />
                      <van-popup position="bottom" round get-container="#app" v-model="item.typeshow">
                        <van-picker title="" show-toolbar item-height="75" :columns="item.viscosity"
                          @confirm="typesConfirm(item.id, $event)" @cancel="item.typeshow = false" />
                      </van-popup>
                    </div>
                  </div>
                </div>
                <div class="titem_cont">
                  <img src="@/assets/img/btn_mix.png" class="paybtn btn_mix"
                    @click="toPay('1', item.count, item.id, item.types)" />
                  <img src="@/assets/img/btn_cash.png" class="paybtn btn_cash"
                    @click="toPay('2', item.count, item.id, item.types)" />
                </div>
              </div>
            </div>
            <!-- 礼品商城 -->
            <div class="tab_container_list clmstart" v-if="tablist[1].isflag">
              <div class="titem" v-for="item in giftlist" :key="item.id">
                <div class="titem_cont">
                  <div class="titem_left">
                    <!-- 左边 -->
                    <div class="pro_box">
                      <div class="pro_bg"></div>
                      <img :src="item.poster_url" />
                    </div>
                    <a class="todetailbtn" href="javascript:;" @click="
                      $router.replace({
                        path: 'goodsdetail',
                        query: { goods_url: item.detail_url },
                      })
                      ">查看详情</a>
                  </div>
                  <!-- 右边 -->
                  <div class="titem_right">
                    <div class="topt title">{{ item.title }}</div>
                    <div class="topt price">金额：￥{{ item.price }}</div>
                    <div class="topt price">
                      混合支付：￥{{ item.discount_price }}+积分{{
                        item.points
                      }}
                    </div>
                    <!-- <div class="topt price">库存：{{ item.stock }}</div> -->
                    <div class="topt count">
                      <span>购买数量：</span>
                      <van-stepper v-model="item.count" integer step="1" :max="item.stock" input-width="62px"
                        button-size="44px" class="stepper" />
                    </div>
                  </div>
                </div>
                <div class="titem_cont">
                  <img src="@/assets/img/btn_mix.png" class="paybtn btn_mix"
                    @click="toPay('1', item.count, item.id, '')" />
                  <img src="@/assets/img/btn_cash.png" class="paybtn btn_cash"
                    @click="toPay('2', item.count, item.id, '')" />
                </div>
              </div>
            </div>
            <!-- 保养系列 -->
            <div class="tab_container_list clmstart" v-if="tablist[2].isflag">
              <div class="titem" v-for="item in carelist" :key="item.id">
                <div class="titem_cont">
                  <div class="titem_left">
                    <div class="pro_box">
                      <div class="pro_bg"></div>
                      <img :src="item.poster_url" />
                    </div>
                    <a class="todetailbtn" href="javascript:;" @click="
                      $router.replace({
                        path: 'goodsdetail',
                        query: { goods_url: item.detail_url },
                      })
                      ">查看详情</a>
                  </div>
                  <div class="titem_right">
                    <div class="topt title">{{ item.title }}</div>
                    <div class="topt price">
                      混合支付：￥{{ item.discount_price }}+积分{{
                        item.points
                      }}
                    </div>
                    <div class="topt count">
                      <span>购买数量：</span>
                      <van-stepper v-model="item.count" integer step="1" input-width="62px" button-size="44px"
                        class="stepper" />
                    </div>
                    <div class="topt types">
                      <span>选择门店：</span>
                      <input type="text" readonly v-model="item.hxpalce.name" @click="item.hxpalceshow = true" />
                      <van-popup position="bottom" round get-container="#app" v-model="item.hxpalceshow">
                        <van-picker title="" show-toolbar item-height="75" :columns="item.stores" value-key="name"
                          @confirm="hxpalceConfirm(item.id, $event)" @cancel="item.hxpalceshow = false" />
                      </van-popup>
                    </div>
                  </div>
                </div>
                <div class="titem_cont">
                  <img src="@/assets/img/btn_now.png" class="paybtn btn_mix"
                    @click="buyCare(item.id, item.count, item.hxpalce.id)" />
                </div>
              </div>
            </div>
          </div>
          <img src="@/assets/img/person_foot.png" class="tab_foot" />
        </div>
      </div>
    </div>
    <!-- 支付状态 -->
    <div class="tkbox pay_status_box clmcenter" v-show="isPay">
      <div class="tk_cont">
        <div class="tk_cont_info clmcenter">
          <img :src="payStatus === 1
            ? require('@/assets/img/dui.png')
            : require('@/assets/img/cuo.png')
            " class="tk_icon" />
          <div class="tk_title">
            {{ payStatus === 1 ? "购买成功" : "支付失败" }}
          </div>
        </div>
      </div>
      <img src="@/assets/img/btn_myorder.png" class="btn_order" @click="$router.replace('/order')" />
    </div>
    <!-- 填写收货地址 -->
    <PostAddr :goods_id="goods_id" :number="number" :payType="payType" :viscosity="viscosity" :addrInfo="addrinfo"
      from="add" @submitCall="submitCallBack" @closeAddr="addrflag = false" v-show="addrflag" />
  </div>
</template>
<script>
import PostAddr from "@/components/PostAddr.vue";
import { Toast } from "vant";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      tablist: [
        { id: "s01", name: "产品商城", isflag: true },
        { id: "s02", name: "礼品商城", isflag: false },
        { id: "s03", name: "保养系列", isflag: false },
      ],
      my_integral: 0, // 我的积分
      // 产品商场
      prolist: [
        // {
        //   id: "p01",
        //   name: "壳牌爱德王子全合成热爱系列",
        //   price: "0.02",
        //   in_price: "0.01",
        //   integral: 500,
        //   count: "1",
        //   img: require("@/assets/img/test1.png"),
        //   types: "10W-30",
        //   typeslist: ["10W-30", "10W-40", "10W-50"],
        //   typeshow: false,
        // },
      ],
      // 礼品商城
      giftlist: [
        // {
        //   id: "g01",
        //   name: "小米充电宝",
        //   price: "0.02",
        //   in_price: "0.01",
        //   integral: 500,
        //   count: "1",
        //   img: require("@/assets/img/test2.png"),
        // },
      ],
      // 保养系列
      carelist: [],
      isPay: false, // 是否支付
      payStatus: 0, // 支付状态
      addrflag: false, // 调起填写收货地址
      payType: "", // 支付类型  1代表混合支付,2代表现金
      number: 1, // 购买数量
      goods_id: "", // 商品id
      viscosity: "", // 粘度
      // 回填地址信息
      addrinfo: {
        name: "",
        phone: "",
        address: "",
      },
    };
  },
  components: {
    PostAddr,
  },
  created() {
    // 获取支付状态
    let paycode = this.$route.query.paycode;
    if (paycode == "payok") {
      this.isPay = true;
      this.payStatus = 1;
    } else if (paycode == "payfail") {
      this.isPay = true;
      this.payStatus = 0;
    }
    // 获取用户积分
    this.my_integral = this.$store.state.my_integral;
    this.prolist = this.$store.state.productList;
    this.giftlist = this.$store.state.giftsList;
    this.carelist = this.$store.state.careList;
    if (this.prolist.length == 0 || this.giftlist.length == 0) {
      // 获取商品列表
      this.getAllGoods();
    }
    // 新增 
    if (this.carelist.length == 0) {
      // 获取保养套餐列表
      this.getAllCareGoods();
    }
  },
  methods: {
    // 获取商品列表
    getAllGoods() {
      Toast.loading({
        message: "loading...",
        forbidClick: true,
        duration: 0, //值为 0 时，toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      this.$http.post("/getAllGoods").then((res) => {
        Toast.clear();
        // console.log(res);
        if (res.data.code == 200) {
          //获取成功
          let info = res.data.data;
          this.my_integral = info.total_points;
          this.$store.commit("updateMyIntegral", info.total_points);
          let plist = info.products;
          let glist = info.gifts;
          let prolist = [];
          let giftlist = [];
          plist.forEach((item) => {
            prolist.push({
              ...item,
              count: 1,
              types: item.viscosity[0],
              typeshow: false,
            });
          });
          this.prolist = prolist;
          this.$store.commit("updateProductList", prolist);
          glist.forEach((item) => {
            giftlist.push({ ...item, count: 1 });
          });
          this.giftlist = giftlist;
          this.$store.commit("updateGiftsList", giftlist);
        } else {
          Toast(res.data.msg);
        }
      });
    },
    // 新增 获取保养套餐列表
    getAllCareGoods() {
      Toast.loading({
        message: "loading...",
        forbidClick: true,
        duration: 0, //值为 0 时，toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      this.$http.post("/getAllCareGoods").then((res) => {
        Toast.clear();
        // console.log(res);
        if (res.data.code == 200) {
          //获取成功
          let info = res.data.data.cares;
          let carelist = [];
          info.forEach((item) => {
            carelist.push({
              ...item,
              count: 1,
              hxpalce: item.stores[0], // 默认核销门店
              hxpalceshow: false,
            });
          });
          this.carelist = carelist;
          this.$store.commit("updateCareList", carelist);
        } else {
          Toast(res.data.msg);
        }
      });
    },
    // 切换商城类型
    change(id) {
      this.tablist.forEach((item) => {
        item.id === id ? (item.isflag = true) : (item.isflag = false);
      });
    },
    // 选择粘度
    typesConfirm(id, val) {
      // console.log(id, val);
      this.prolist.some((item) => {
        if (item.id === id) {
          item.types = val;
          item.typeshow = false;
        }
      });
    },
    // 新增 保养套餐 选择门店
    hxpalceConfirm(id, val) {
      // console.log(id, val);
      this.carelist.some((item) => {
        if (item.id === id) {
          item.hxpalce = val;
          item.hxpalceshow = false;
        }
      });
    },
    // 去支付
    toPay(type, number, goods_id, types) {
      this.payType = type;
      this.number = number;
      this.goods_id = goods_id;
      this.viscosity = types;
      // 回填地址信息
      this.$http
        .post("/getLastReceiverInfoToMall")
        .then((res) => {
          // console.log(res);
          if (res.data.code == 200) {
            let rst = res.data.data;
            if (rst.existReceiverInfo === 1) {
              this.addrinfo = {
                name: rst.info.receiver,
                phone: rst.info.phone,
                address: rst.info.address,
              };
            }
            this.addrflag = true;
          } else {
            Toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 地址提交成功后
    submitCallBack(orderid, noncestr) {
      this.addrflag = false;
      this.Pay(orderid, noncestr);
    },
    // 支付
    Pay(orderid, noncestr) {
      // 判断是是否在小程序内打开
      var ua = navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        //ios的ua中无miniProgram，但都有MicroMessenger（表示是微信浏览器）
        wx.miniProgram.getEnv((res) => {
          if (res.miniprogram) {
            //在微信内，在小程序内。
            console.log("小程序的支付业务");
            // let wxJson = {}; // 微信返回的参数
            // 跳转到小程序的支付页面
            wx.miniProgram.navigateTo({
              // url: `/pages/pay/pay?type=${this.payType}&number=${this.number}&goods_id=${this.goods_id}`,
              url: `/pages/pay/pay?orderid=${orderid}&noncestr=${noncestr}&from=store`,
            });
            return;
          } else {
            //在微信内，不在小程序内。
            console.log("微信H5的支付业务");
            return;
          }
        });
      } else {
        //不在微信内。
        console.log("第三方浏览器支付业务");
        return;
      }
    },
    // 新增 购买保养套餐
    buyCare(care_id, number, hxpalce_id) {
      // console.log(care_id, number, hxpalce_id);
      let data = {
        care_id: care_id,
        number: number,
        store_id: hxpalce_id,
      };
      Toast.loading({
        message: "loading...",
        forbidClick: true,
        duration: 0, //值为 0 时，toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      this.$http.post("/buyCareGoods", data).then((res) => {
        Toast.clear();
        if (res.data.code == 200) {
          // 支付
          let orderid = res.data.data.out_trade_no;
          let noncestr = res.data.data.noncestr;
          this.Pay(orderid, noncestr);
        } else {
          Toast(res.data.msg);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.store {
  overflow-y: scroll;

  .noticebox {
    position: absolute;
    top: 2rem;
    right: 0;
    width: calc(100% - 180px);
    height: 76px;
  }

  .store_container {
    position: relative;
    width: 100%;
    height: auto;
    margin: 10rem 0 7rem;

    .store_tabs {
      width: 678px;
      height: auto;
      margin: 0 auto;

      .tab_title_box {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;

        .tab_title_item {
          width: 215px;
          height: 105px;
          background: url("@/assets/img/tab_default.png") no-repeat;
          background-size: 100% auto;
          font-size: 2.5rem;
          color: #fbce07;
          text-align: center;
          line-height: 92px;
          font-family: "Alimama_ShuHeiTi_Bold";
          font-weight: normal;
          cursor: pointer;
        }

        .active {
          background: url("@/assets/img/tab_active.png") no-repeat;
          background-size: 100% auto;
          color: #e6111c;
        }
      }

      .tab_container_box {
        width: 100%;
        margin-top: -2rem;

        .tab_head,
        .tab_foot {
          width: 100%;
        }

        .tab_container,
        .tab_foot {
          margin-top: -1px;
        }

        .tab_container {
          width: 100%;
          background-color: #e9e8eb;
          border: 10px solid #e6111c;
          box-sizing: border-box;
          border-top-style: none;
          border-bottom-style: none;

          // 我的积分
          .my_integral {
            width: 583px;
            text-align: left;
            font-size: 2rem;
            padding-left: 3rem;
            padding-top: 1rem;
          }

          .tab_container_list {
            width: 100%;
            padding: 2rem 0;

            .titem {
              width: 583px;
              height: auto;
              background-color: #f7f7f7;
              border: 5px solid #ffffff;
              box-sizing: border-box;
              box-shadow: 0 5px 10px 0px rgba(81, 0, 0, 0.52);
              padding: 1rem;
              margin-bottom: 2rem;

              .titem_cont {
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 1.4rem;

                .titem_left,
                .titem_right {
                  height: 100%;
                  display: flex;
                  flex-flow: column nowrap;
                  justify-content: center;
                  align-items: center;
                }

                .titem_left {
                  width: 37%;

                  .pro_box {
                    position: relative;
                    width: 100%;
                    height: 210px;
                    display: flex;
                    justify-content: center;
                    align-items: flex-end;

                    .pro_bg {
                      position: absolute;
                      width: 190px;
                      height: 190px;
                      background: #fbce07;
                      border-radius: 50%;
                    }

                    img {
                      position: relative;
                      z-index: 2;
                      margin-bottom: -0.5rem;
                      width: 190px;
                      height: 210px;
                      object-fit: contain;
                    }
                  }

                  // 查看详情
                  a.todetailbtn {
                    color: #404040;
                    padding-top: 1rem;
                    text-decoration: none;
                    border-bottom: 1px solid #0a0a0a;
                  }
                }

                .titem_right {
                  justify-content: flex-start;
                  width: calc(100% - 37%);
                  overflow: hidden;
                  padding-left: 1rem;

                  .topt {
                    width: 100%;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    margin-bottom: 0.5rem;
                  }

                  .title {
                    font-size: 2rem;
                    line-height: 1.2;
                    font-family: "AlibabaPuHuiTi-2-85-Bold";
                    width: 100%;
                    height: 85px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                  }

                  .price {
                    color: #959797;
                  }

                  .count {
                    .stepper {
                      button {
                        background-color: #e1e1e1;
                      }
                    }
                  }

                  // 选择粘度
                  .types {
                    input {
                      width: 160px;
                      height: 44px;
                      background-color: #e1e1e1;
                      border: none;
                      text-align: center;
                    }
                  }

                  // 支付按钮
                  .buybtn {
                    margin-top: 1rem;
                  }
                }

                // 支付按钮
                .paybtn {
                  margin-top: 1rem;
                }

                .btn_cash {
                  margin-left: 3rem;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
<style>
.van-picker__cancel,
.van-picker__confirm,
.van-picker__title,
.van-picker-column {
  font-size: 2rem !important;
}

.van-picker__title {
  line-height: 36px !important;
}

.van-picker__toolbar {
  height: 70px !important;
}

.van-radio {
  align-items: flex-start !important;
}

.van-radio__label {
  line-height: 1.2 !important;
}

/* 步进器 */
.van-stepper__minus,
.van-stepper__plus,
.van-stepper__input {
  background-color: #e2e3e3 !important;
}

.van-stepper__input {
  font-size: 1.8rem !important;
  margin: 0 5px !important;
}
</style>
